package viewcontrollers;

import pojos.Employees;
import viewcontrollers.util.JsfUtil;
import viewcontrollers.util.PaginationHelper;
import beans.EmployeesFacade;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import util.SendMail;

@ManagedBean(name = "employeesController")
@SessionScoped
public class EmployeesController implements Serializable {

    private String businessEmail;
    private String password;
    private SecureRandom random;
    private Employees current;
    private DataModel items = null;
    private DataModel searchItems = null;
    private String searchText;
    @EJB
    private beans.EmployeesFacade ejbFacade;
    private PaginationHelper pagination;
    private PaginationHelper searchPagination;
    private int selectedItemIndex;

    public Employees getCurrent() {
        return current;
    }

    public void setCurrent(Employees current) {
        this.current = current;
    }

    public EmployeesController() {
    }

    public String getBusinessEmail() {
        return businessEmail;
    }

    public void setBusinessEmail(String businessEmail) {
        this.businessEmail = businessEmail;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Employees getSelected() {
        if (current == null) {
            current = new Employees();
            selectedItemIndex = -1;
        }
        return current;
    }

    private EmployeesFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Employees) getItems().getRowData();
        System.out.println("########### Current Row is: " + current.getBusinessEmail());
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Employees();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EmployeesCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Employees) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EmployeesUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Employees) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EmployeesDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
        searchItems = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Employees.class)
    public static class EmployeesControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            EmployeesController controller = (EmployeesController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "employeesController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Employees) {
                Employees o = (Employees) object;
                return getStringKey(o.getEmpId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + EmployeesController.class.getName());
            }
        }
    }

    public String getSearchText() {
        return searchText;
    }

    public void setSearchText(String searchText) {
        this.searchText = searchText;
    }

    public String search() {
        return "searchemployees";
    }

    public PaginationHelper getSearchPagination() {
        if (searchPagination == null) {
            searchPagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().searchEmployees(searchText));
                }
            };
        }
        return searchPagination;
    }

    public DataModel getSearchItems() {
        System.out.println(" getting Search ");
        searchItems = null;
        if (searchItems == null) {
            searchItems = getSearchPagination().createPageDataModel();
            items = searchItems;
        }
        return items;
    }

    /**
     * Reset Employee Password
     * @return String
     */
    public String resetPassword() {
        current = (Employees) getItems().getRowData();
        String generatedPassword = generateRandomPassword();
        current.setPassword(generatedPassword);
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        try {
            String employeeMail = current.getBusinessEmail();
            sendMail(generatedPassword, employeeMail);
            performResetting();
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        recreateModel();
        return "List";
    }

    /**
     * Generate Random Password...
     * @return String
     */
    public String generateRandomPassword() {
        random = new SecureRandom();
        return new BigInteger(40, random).toString(12);
    }

    /**
     * Updating the Employee Password...
     */
    private void performResetting() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EmployeesPasswordResetted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    /**
     * Send Confirmation Mail to the Employee 
     * with the New Password...
     * 
     */
    public void sendMail(String newPassword, String employeeMail) {
        System.out.println("Sending");
        String to = employeeMail;
        String subject = "New Password";
        String message = "Dear MR/MS " + employeeMail + "\n" + "Your New Login Password is [" + newPassword + "]" + "\n" + "Thanks" + "\n" + "Aquantima Support";
        SendMail sm = new SendMail();
        sm.send(to, subject, message);
        System.out.println("Sent.");
    }

    /**
     * this Method will check User Name and Password
     * to detect Valid Login from Invalid Login...
     * @return String 
     */
    public String loginCheck() {
        String userName = getBusinessEmail();
        String pass = getPassword();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        Employees emp = getFacade().checkUserLogin(userName, pass);
        if (emp != null) {
            session.putValue("type", emp.getType());
            session.putValue("userName", emp.getBusinessEmail());
            session.putValue("password", emp.getPassword());
            session.putValue("empid", emp.getEmpId());
            session.putValue("firstName", emp.getFirstName());
        }
        if (emp != null && emp.getType().equalsIgnoreCase("admin")) {
            return "index";
        } else {
            if (emp != null && emp.getType().equalsIgnoreCase("user")) {
                return "userhome";
            } else {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("InvalidLogin"));
                return null;
            }
        }
    }

    public Employees getEmployeeByBusninessMail(String businessEmail) {
        System.out.println("######################Employee Mail: " + businessEmail);
        Employees emp = getFacade().searchEmployee(businessEmail);
        System.out.println("#################Emp ID: " + emp.getEmpId());
        return emp;
    }

    public String logOut() {
        try {
            System.out.println("////////////////// LogOut Method //////////////////");
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            session.invalidate();
            return "/login";
        } catch (Exception e) {
            e.printStackTrace();
            return "/login";
        }
    }

    /**
     * View Employee Profile...
     * @return String
     */
    public String viewProfile() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        String userName = session.getAttribute("userName").toString();
        String pass = session.getAttribute("password").toString();
        Employees emp = getFacade().checkUserLogin(userName, pass);
        current = emp;
        return "/viewprofile";
    }

    /**
     * Update Employee Profile...
     * @return String
     */
    public String updateProfile() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EmployeesUpdated"));
            return "/viewprofile";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public List<String> autocomplete(String inputValue) {
        List<Employees> objList = getFacade().searchEmployees(inputValue);
        List<String> empBusinessEmails = new ArrayList<String>();
        for (Iterator<Employees> it = objList.iterator(); it.hasNext();) {
            Employees emp = it.next();
            empBusinessEmails.add(emp.getBusinessEmail());
        }
        return empBusinessEmails;
    }
}
